package insight.web.delegates;

import java.io.OutputStreamWriter;
import java.io.Writer;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

/**
 * 
 * AjaxJSONDelegate class set json object in HttpServletResponse and send back
 * to the UI.
 * 
 */
public class AjaxJSONDelegate {

	/**
	 * 
	 * @param jarray
	 *            holds the response values
	 * @param res
	 *            is HttpServletResonse.
	 */
	public static void setResponse(final JSONArray jarray,
			final HttpServletResponse res) {
		try {
			Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8");
			w.write(jarray.toString());
			w.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 
	 * @param content
	 *            holds the response values
	 * @param res
	 *            is HttpServletResonse.
	 */
	public static void setTextResponse(final String content,
			final HttpServletResponse res) {
		try {
			Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8");
			w.write(content);
			w.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 
	 * @param jsonStringer
	 *            holds response values
	 * @param res
	 *            is HttpServletResonse.
	 */
	public static void setResponse(final JSONStringer jsonStringer,
			final HttpServletResponse res) {
		try {
			Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8");
			w.write(jsonStringer.toString());
			w.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static void setResponse(final JSONObject obj,
			final HttpServletResponse res) {
		try {
			Writer w = new OutputStreamWriter(res.getOutputStream(), "utf-8");
			// System.out.print(obj.toString());
			w.write(obj.toString());
			w.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 
	 * @param response
	 * @param message
	 * @param errorData
	 */
	public static void reportError(HttpServletResponse response,
			String message, JSONObject errorData) {
		JSONObject returnObj = new JSONObject();
		try {
			returnObj.put("success", false).put("error", message);

			if (errorData != null)
				returnObj.put("errorData", errorData);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		AjaxJSONDelegate.setResponse(returnObj, response);
	}
}
